package host.springboot.framework.autoconfigure.mybatisplus;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import host.springboot.framework.autoconfigure.mybatisplus.filter.DruidAdvertFilter;
import host.springboot.framework.core.util.inner.StringUtils;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MybatisPlus自动配置
 *
 * @author JiYinchuan
 * @since 1.0.0
 */
@Configuration(proxyBeanMethods = false)
@AutoConfiguration(before = MybatisPlusAutoConfiguration.class)
public class KsMybatisPlusAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public PaginationInnerInterceptor paginationInnerInterceptor() {
        return new PaginationInnerInterceptor(DbType.MYSQL);
    }

    /**
     * Druid广告拦截配置
     *
     * <p>该过滤器主要用于去掉 [druid] 网页中的底部广告内容
     *
     * @author JiYinchuan
     * @see DruidAdvertFilter
     * @since 1.0.0
     */
    @ConditionalOnClass(DruidDataSourceAutoConfigure.class)
    @AutoConfiguration(after = DruidDataSourceAutoConfigure.class)
    @ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true", matchIfMissing = true)
    static class DruidAdvertConfiguration {

        @Bean
        @ConditionalOnBean(DruidStatProperties.class)
        public FilterRegistrationBean<DruidAdvertFilter> removeDruidAdvert(DruidStatProperties properties) {
            // 获取Web监控页面参数
            DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
            // 提取common.js配置路径
            String pattern = StringUtils.isNotBlank(config.getUrlPattern()) ? config.getUrlPattern() : "/druid/*";
            String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");

            FilterRegistrationBean<DruidAdvertFilter> registrationBean = new FilterRegistrationBean<>();
            registrationBean.setFilter(new DruidAdvertFilter());
            registrationBean.addUrlPatterns(commonJsPattern);
            return registrationBean;
        }
    }
}
